import React,{useEffect,useState} from 'react'
import {View,Text,TouchableOpacity,StyleSheet,ImageBackground,FlatList,TextInput,Modal, AsyncStorage,Alert} from 'react-native';
import { Input, Icon ,Button} from '@rneui/themed';
import { AntDesign,Ionicons,Entypo,FontAwesome   } from '@expo/vector-icons';
import AsyncStorge from '@react-native-async-storage/async-storage' 
import '../../global'
import { useSelector } from 'react-redux';
import {useToDoList} from '../../context'
const showAlert = (msg,fun) =>
  Alert.alert(
    "提示",
    msg,
    [
      {
        text: "确认",
        onPress: fun,
        style: "cancel",
      },
    ],
    {
      cancelable: false,
    }
  );

const week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
const imgList = [
    'https://images.pexels.com/photos/807598/pexels-photo-807598.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
    'https://images.pexels.com/photos/360912/pexels-photo-360912.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260',
    'https://images.pexels.com/photos/378570/pexels-photo-378570.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
    'https://images.pexels.com/photos/1757363/pexels-photo-1757363.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
    'https://images.pexels.com/photos/6004828/pexels-photo-6004828.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
    'https://images.pexels.com/photos/3389955/pexels-photo-3389955.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
]
const phrase = [
    '一个人能观察落叶、鲜花，从细微处欣赏一切，生活就不能把他怎么样。',
    '星光不负赶路人',
    '少年不惧岁月长，彼方尚有荣光在',
    '今天不想跑，所以才去跑',
    '无人问津也好、技不如人也罢，你要试着安静下来，做自己该做的事，而不是让内心烦躁、焦虑，毁掉你本就不多的热情和动力',
    '努力只能及格，拼命才能优秀'
]



const getCurrentDay = () =>{
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
    }
    let currentdate = year + '-' + month + '-' + strDate;
    return currentdate;
}

const getDays = (start,end) => {
    let day1 = Date.parse(start);
    let day2 = Date.parse(end);
    if(day1>day2){
        return 0;
    }
    if(day1==day2){
        return 1;
    }
    let days = (day2-day1)/(1*24*60*60*1000);
    return days-1;
}

let num = Math.floor(Math.random()*6);

let imgURL= require('../../assets/image/mountain.jpg');
let day= getDays(getCurrentDay(),'2022-12-24');

let date = new Date();
let arr = [];
let q=date.getDate();
let x = date.getDay();
arr[x]=q;
let count=1;
let count1=1;
for(var i = x-1;i>=0;i--){
    arr[i]=q-count;
    count++;
}
for(var i = x+1;i<7;i++){
    arr[i]=q+count1;
    count1++;
}



const Home = ({navigation}) => {
    const [judge,setJudge] = useState(false);
    const {todoList,setToDoList} = useToDoList();
    const [modalVisible, setModalVisible] = useState(false);
    const [message,setMessage] = useState({});
    const list=useSelector(state=>state.list)
    /*----------------------------------*/
    const renderItem = ({item}) => {
        if(q==item || week[x] == item){
            return <View style={{width:changeW(70),display:'flex',alignItems:'center'}}><Text style={{color:'white',fontWeight:'bold',fontSize:changeW(28)}}>{item}</Text></View>
        }
            return <View style={{width:changeW(70),display:'flex',alignItems:'center'}}>
                <Text style={{color:'white',fontSize:changeW(20)}}>{item}</Text>
                </View>
    }
/*--------------学习任务列表------------------------------------*/
    const List = () =>{
        
        // console.log(todoList)
        /*--------没有学习任务时-------------------------------*/
    if(todoList.length==0 || todoList.length==1&&todoList[0].finish ==true){
        return (
            <TouchableOpacity style={{display:'flex',flexDirection:'row',alignItems:'center',width:'100%',height:'100%',justifyContent:'center'}}
            
            onPress={()=>{
                if(list.isLogin==false){
                    showAlert('请先登录！',()=>navigation.navigate('Login'))
                }else{
                    navigation.navigate('Task')
                }
                
            }}
            >
                <View style={styles.write}>
                    <FontAwesome name="pencil-square-o" size={28}/>
                </View>
                <View style={{marginLeft:changeW(15)}}>
                    <Text style={{fontSize:changeW(23)}}>添加学习任务</Text>
                    <Text style={{color:'grey'}}>每日离梦想更近一步</Text>
                </View>
            </TouchableOpacity>
        )
    }
    return <View>
        <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => {
                Alert.alert("Modal has been closed.");
                setModalVisible(!modalVisible);
        }}
      >
        <View>
          <View style={{backgroundColor:'white',borderRadius:20,
          shadowOpacity: 0.25,shadowRadius: 3.84, elevation: 5,
          width:'75%',shadowColor: "#000", shadowOffset: {width: 0,height: 2},height:changeH(450),top:0.2*h,left:0.13*w}}>
                <Text style={{color:'#4F4F4F',fontSize:changeW(30),fontWeight:'bold',textAlign:'center',marginTop:changeH(20)}}>详情</Text>
                <Text style={{color:'#4F4F4F',fontSize:changeW(25),fontWeight:'bold',marginTop:changeH(25),marginRight:changeW(10),marginLeft:changeW(25)}}>任务名称：{message.title}</Text>
                <Text style={{color:'#4F4F4F',fontSize:changeW(25),fontWeight:'bold',marginTop:changeH(25),marginRight:changeW(10),marginLeft:changeW(25)}}>备注：{message.content}</Text>
                <Text style={{color:'#4F4F4F',fontSize:changeW(25),fontWeight:'bold',marginTop:changeH(25),marginRight:changeW(10),marginLeft:changeW(25)}}>时间：{message.time}</Text>
            <TouchableOpacity 
            style={{backgroundColor:'#EECFA1',width:'40%',height:changeH(80),marginTop:changeH(20),borderRadius:5,display:'flex',justifyContent:'center',alignItems:'center',left:'30%'}}
              onPress={() => {
                setModalVisible(!modalVisible);
              }}
            >
              <Text style={{color:'white',fontSize:changeW(35),fontWeight:'bold'}}>确认</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>



        <FlatList
        data={todoList}
        keyExtractor={index => index}
        renderItem={({index,item}) => {
            
                return (
                    <View>
                    <View style={{width:'100%',height:changeH(80),display:'flex',flexDirection:'row',alignItems:'center',flexWrap:'nowrap'}}>
                        <Entypo name='circle' size={23} style={{marginLeft:changeW(10),marginRight:changeW(10)}}
                            onPress={()=>{
                                item.finish=!item.finish;
                                let i = index;
                                setJudge(!judge);
                                todoList.splice(index,1);
                                AsyncStorage.setItem('getToDoList',JSON.stringify(todoList));
                        }}
                        />
                        <TouchableOpacity style={{width:'90%',display:'flex',flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}
                        onPress={()=>{
                            setMessage({
                                title:item.content,
                                content:item.addCon,
                                time:item.time
                            })
                            setModalVisible(true);
                        }}
                        >
                        <Text style={{fontSize:changeW(25),width:'48%'}} ellipsizeMode='tail'numberOfLines={1}>{item.content}</Text>
                        <Text>{item.time}</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={{width:'100%',height:changeH(3),backgroundColor:'rgb(249,249,249)'}}></View>
                    </View>
                )
        }
        }
        />
    </View>
}
    return (
        <View style={{backgroundColor:'rgb(249,249,249)'}}>
            <ImageBackground style={styles.bgimage} source={{uri:imgList[num]}}>
                <View style={{backgroundColor:'rgba(0,0,0,0.4)',width:'100%',height:'100%',position:'relative'}}>
                <View style={{width:'100%',display:'flex',flexDirection:'row',justifyContent:'space-around',marginTop:changeH(50)}}>
                    <View style={{marginTop:changeH(70),marginLeft:changeW(120),width:'60%'}}>
                        <Text style={{color:'white',fontSize:changeW(55)}}>{day}天</Text>
                        <Text style={{color:'white',fontWeight:'bold'}}>2023考研倒计时</Text>
                        <Text style={{color:'white',marginTop:'5%',fontSize:changeW(25)}}>{phrase[4]}</Text>
                    </View>
                    <View style={{marginTop:changeH(110)}}>
                        <Button
                            title="打卡"
                            buttonStyle={{
                                backgroundColor: 'rgba(123,123,123,0.8)',
                                borderRadius: 30,
                            }}
                            containerStyle={{
                                width: changeW(150),
                                marginHorizontal: 50,
                                marginVertical: 10,
                            }}
                            titleStyle={{ fontWeight: 'bold' }}
                            onPress={()=>{if(list.isLogin==false){
                                showAlert('请先登录！',()=>navigation.navigate('Login'))
                            }else{
                                navigation.navigate('Check')
                            }}}
                />
                        </View>
                </View>
                      
                <View>
                    <View style={{position:'absolute',top:changeH(10)}}>
                    <FlatList 
                        data={week}
                        keyExtractor={index => index}  
                        horizontal={true}
                        contentContainerStyle={{justifyContent:'space-around',width:'100%'}}  
                        renderItem={renderItem}
                    />
                    </View>
                    <View style={{position:'absolute',top:changeH(45)}}>
                    <FlatList
                        data={arr}
                        horizontal={true}
                        keyExtractor={index => index}
                        contentContainerStyle={{justifyContent:'space-around',alignItems:'center',width:'100%',marginTop:changeH(0)}}
                        renderItem={renderItem}
                    />
                    </View>
                </View>
                </View>
            </ImageBackground>
            <View style={styles.second}>
            {/* onPress={onPress} */}
            <View style={styles.tabStyle}>
                <TouchableOpacity style={styles.button} onPress={()=>navigation.navigate('College')}>
                    <Ionicons name='school-outline' size={40} color='rgb(63,63,63)'/>
                </TouchableOpacity>
                <Text style={styles.text}>院校</Text>
            </View>
           <View style={styles.tabStyle}>
                <TouchableOpacity style={styles.button} onPress={()=>{if(list.isLogin==false){
                                showAlert('请先登录！',()=>navigation.navigate('Login'))
                            }else{
                                navigation.navigate('Word')
                            }}}>
                <Entypo name="hour-glass" size={30} color='rgb(63,63,63)' />
                </TouchableOpacity>
                <Text style={styles.text}>背单词</Text>
           </View>
            <View style={styles.tabStyle}>
                <TouchableOpacity style={styles.button} onPress={()=>navigation.navigate('Ency')}>
                    <Ionicons name='bookmark-outline' size={30} color='rgb(63,63,63)'/>
                </TouchableOpacity>
                <Text style={styles.text}>百科</Text>
            </View>
            <View style={styles.tabStyle}>
                <TouchableOpacity style={styles.button} onPress={()=>navigation.navigate('Book')}>
                    <AntDesign name='book' size={30} color='rgb(63,63,63)'/>
                </TouchableOpacity>
                <Text style={styles.text}>参考书</Text>
            </View>
            
            </View>
            <View style={{backgroundColor:'white',height:changeH(780),width:'100%',marginTop:changeH(15)}}>
                <Text style={styles.text0}>今日任务</Text>
                <View style={{width:'100%',height:changeH(3),backgroundColor:'rgba(63,63,63,0.1)',marginTop:changeH(10)}}></View>
                <View style={{width:'30%',display:'flex',flexDirection:'row',justifyContent:'space-around'}}>
                    <AntDesign name='clockcircle' size={20} color='rgb(204,190,151)'style={{marginTop:changeH(5)}}/>
                    <Text style={{fontSize:changeW(25)}}>我的学习任务</Text>
                    <Text style={styles.text1}  onPress={()=>{
                if(list.isLogin==false){
                    showAlert('请先登录！',()=>navigation.navigate('Login'))
                }else{
                    navigation.navigate('Task')
                }
            }}>+添加</Text>
                </View>
                <View style={{width:'100%',height:changeH(610),marginTop:changeH(30),display:'flex'}}>
                        <List/>
                </View>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    bgimage:{
        width:'100%',
        height:changeH(510)
    },
    second:{
        backgroundColor:'white',
        display:'flex',
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'space-around',
        height:changeH(200),
        width:'100%'
    },
    button:{
        backgroundColor:'rgb(237,237,237)',
        display:'flex',
        justifyContent:'center',
        alignItems:'center',
        width:changeH(110),
        height:changeH(110),
        borderRadius:50
    },
    tabStyle:{
        display:'flex',
        alignItems:'center'
    },
    text:{
        marginTop:changeH(10)
    },
    text0:{
        fontSize:changeW(25),
        fontWeight:'bold',
        marginTop:changeH(15),
        marginLeft:changeW(10)
    },
    text1:{
        fontSize:changeW(23),
        color:'rgb(204,190,151)',
        position:'absolute',
        right:changeW(-490),
        top:changeH(0)
    },
    write:{
        width:changeH(90),
        height:changeH(90),
        borderRadius:50,
        display:'flex',
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'rgb(237,237,237)',
    }
})

export default Home
